#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"

static SListNode* NewNode(DataType x)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
	newnode->data = x;
	newnode->next = NULL;
}

void InitSListNode(SListNode* phead)
{
	phead->next = NULL;
	phead->data = -1;
}

void PushBackNode(SListNode** pphead, DataType x)
{
	assert(pphead);
	SListNode* newnode = NewNode(x);
	SListNode* cur = *pphead;
	while (cur->next != NULL)
	{
		cur = cur->next;
	}
	cur->next = newnode;
}

void PrintNode(SListNode** pphead)
{
	assert(pphead);
	assert((*pphead)->next != NULL);
	SListNode* cur = (*pphead)->next;
	while (cur)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}


int PrintNodeLength(SListNode** pphead)
{
	assert(pphead);
	int count = 0;
	if ((*pphead)->next == NULL)
	{
		return count;
	}
	SListNode* cur = (*pphead)->next;
	while (cur)
	{
		count++;
		cur = cur->next;
	}
	return count;
}


void PrintFind(SListNode** pphead, int i, int length)
{
	assert(pphead);
	assert(length != 0);
	assert(i > 0 && i <= length);
	SListNode* cur = (*pphead)->next;
	while (cur&&i>1)
	{
		i--;
		cur = cur->next;
	}
	printf("%d\n", cur->data);
}


void InsertListNode(SListNode** pphead, int i, int length, DataType x)
{
	assert(pphead);
	assert(length != 0);
	assert(i > 0 && i <= length);
	SListNode* cur = (*pphead)->next;
	while (cur && i > 2)
	{
		i--;
		cur = cur->next;
	}
	SListNode* newnode = NewNode(x);
	newnode->next = cur->next;
	cur->next = newnode;
}

void DeleteListNode(SListNode** pphead, int i, int length)
{
	assert(pphead);
	assert(length != 0);
	assert(i > 0 && i <= length);
	SListNode* cur = (*pphead)->next;
	while (cur && i > 1)
	{
		i--;
		cur = cur->next;
	}
	SListNode* prev = *pphead;
	while (prev->next != cur)
	{
		prev = prev->next;
	}
	prev->next = cur->next;
	free(cur);
	cur = NULL;
}

void DestroyListNode(SListNode** pphead)
{
	assert(pphead);
	SListNode* cur = *pphead;
	while (cur)
	{
		SListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	*pphead = NULL;
}